package com.qingzhu.controller.goodsserver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingzhu.DefalutUrl;
import com.qingzhu.pojo.Goods;
import com.qingzhu.pojo.Item;
import com.qingzhu.service.GoodsService;
import com.qingzhu.service.impl.GoodsServiceImpl;
import com.qingzhu.util.ParamsToObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

// 配置该注解为了实现图片的上传
@MultipartConfig(
        /* 1MB=1024KB(即：1兆字节=1024千字节)
           1KB=1024Byte(即：1千字节=1024字节)
           1Byte=8bit(即：1字节=8位)
           =API= location属性，设置文件上传的默认地址 */
        maxFileSize=1024*1024*5,        // 限制上传文件的大小。1024*1024表示1mb(兆)，默认-1表示无限大小
        maxRequestSize=1024*1024*5*5,   // 设置上传请求中,数据的总大小限制,单位: 字节
        fileSizeThreshold=1024*1024     // 如果文件的大小超过指定的阈值，文件将会被写出到磁盘,单位: 字节
)
@WebServlet("/admin/goods/add")
public class AdminAddGoodsController extends HttpServlet implements DefalutUrl {
    GoodsService goodsService = new GoodsServiceImpl();
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("添加商品..");
        String server = req.getParameter("server");
        // 接收浏览器发送过来的文件上传域
        Part part = req.getPart("addimg");
        // 获取上传文件的原始文件名(文件名)
        String submittedFileName = part.getSubmittedFileName();
        // 拼接图片的上传地址
        String itemImageUrl = HFSURL+"/phone/"+submittedFileName;
        // 成功后需要响应的js语句
        String respStr = null;
        // 获取访问地址
        String origin = req.getHeader("Origin");
        // 如果添加的是单品，则只添加SKU
        if (server.equals("item")) {
            String goodsId = req.getParameter("goodsId");
            Item item = ParamsToObject.getItem(req);
            item.setImage(itemImageUrl);
            goodsService.addItem(Integer.parseInt(goodsId),item);
            respStr = "<script>" +
                    "alert('添加成功！');" +
                    "location.href='"+origin+"/productPage/addProduct.html?goodsId="+goodsId+"';" +
                    "</script>";
        }else {
            Goods goods = ParamsToObject.getGoods(req);
            Item item = ParamsToObject.getItem(req);
            item.setImage(itemImageUrl);
            goodsService.addGoods(goods,item);
            respStr = "<script>" +
                    "alert('添加成功！');" +
                    "location.href='"+origin+"/productPage/addProduct.html';" +
                    "</script>";
        }
        resp.getWriter().write(respStr);
    }
}
